package com.itheima.reggie.service.impl;

import com.itheima.reggie.dao.ShoppingCartDao;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired(required = false)
    private ShoppingCartDao shoppingCartDao;

    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
        // 根据用户的id与菜品的id或者套餐id查询购物项
        ShoppingCart dbshoppingCart = shoppingCartDao.findByUserIdAndDishIdOrSetmeanId(shoppingCart);
        // 如果不存在该购物项，代表该客户是第一次购买该商品，直接插入
        if (dbshoppingCart == null){
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartDao.save(shoppingCart);
            dbshoppingCart = shoppingCart;
        }else {
        // 如果存在该购物项，代表之前该用户已经购买过该商品，直接更新数量
            dbshoppingCart.setNumber(dbshoppingCart.getNumber()+1);
            shoppingCartDao.update(dbshoppingCart);
        }
        // 返回该购物项
        return dbshoppingCart;
    }

    @Override
    public List<ShoppingCart> list(Long userId) {
        List<ShoppingCart> shoppingCartList = shoppingCartDao.findByUserId(userId);
        return shoppingCartList;
    }

    @Override
    public void clean(Long userId) {
        shoppingCartDao.deleteByUserId(userId);
    }
}